package com.warrior.service;

import com.warrior.Exception.ProjectException;
import com.warrior.entity.*;
import com.warrior.respository.IActivityContentRepository;
import com.warrior.respository.IActivityRepository;
import com.warrior.respository.IUserActivityRepository;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Shawn on 2017/3/16.
 */
@Service
public class ActivityService {

    private static final Logger logger = LogManager.getLogger(ActivityService.class.getName());

    @Autowired
    private IActivityRepository activityRepository;

    @Autowired
    private IActivityContentRepository activityContentRepository;

    @Autowired
    private MatchDetailsService matchDetailsService;

    @Autowired
    private UserService userService;

    @Autowired
    private TicketService ticketService;

    @Autowired
    private IUserActivityRepository iUserActivityRepository;

    /**
     * 添加/更新一个活动
     *
     * @param activityEntity 活动对象
     */
    @Transactional
    public void saveNewActivity(ActivityEntity activityEntity) {
        if (logger.isDebugEnabled()) {
            logger.debug("saveNewActivity(ActivityEntity activityEntity={}) - start", activityEntity); //$NON-NLS-1$
        }
        this.activityRepository.save(activityEntity);
        if (logger.isDebugEnabled()) {
            logger.debug("saveNewActivity(ActivityEntity) - end"); //$NON-NLS-1$
        }
    }

    /**
     * 根据一个id找到一个活动
     *
     * @param id 活动id
     * @return ActivityEntity
     */
    @Transactional(readOnly = true)
    public ActivityEntity findActivityById(String id) {
        if (logger.isDebugEnabled()) {
            logger.debug("findActivityById(String id={}) - start", id); //$NON-NLS-1$
        }

        ActivityEntity returnActivityEntity = this.activityRepository.findActivityEntityById(id);
        if (logger.isDebugEnabled()) {
            logger.debug("findActivityById(String) - end"); //$NON-NLS-1$
        }
        return returnActivityEntity;
    }


    /**
     * 找到该活动的具体内容
     *
     * @param activityId 活动id
     * @return List<ActivityContentEntity>
     */
    @Transactional
    public List<ActivityContentEntity> findAllContentByActivityId(String activityId) {
        if (logger.isDebugEnabled()) {
            logger.debug("findAllContentByActivityId(String activityId={}) - start", activityId); //$NON-NLS-1$
        }

        List<ActivityContentEntity> activityContentEntities = null;
        ActivityEntity activityEntity = this.findActivityById(activityId);
        if (null != activityEntity) {
            activityContentEntities = this.activityContentRepository.findAllContentByActivityByActivityIdOrderByActivitySequence(activityEntity);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("findAllContentByActivityId(String) - end"); //$NON-NLS-1$
        }
        return activityContentEntities;
    }

    /**
     * 保存活动内容
     *
     * @param activityContentEntity 活动内容entity
     * @return ActivityContentEntity
     */
    @Transactional
    public ActivityContentEntity saveActivityContent(ActivityContentEntity activityContentEntity) {
        if (logger.isDebugEnabled()) {
            logger.debug("saveActivityContent(ActivityContentEntity activityContentEntity={}) - start", activityContentEntity); //$NON-NLS-1$
        }

        this.activityContentRepository.save(activityContentEntity);

        if (logger.isDebugEnabled()) {
            logger.debug("saveActivityContent(ActivityContentEntity) - end"); //$NON-NLS-1$
        }
        return activityContentEntity;
    }

    /**
     * 根据内容id查找
     * @param contentId 内容id
     * @return ActivityContentEntity
     */
    @Transactional
    public ActivityContentEntity findActivityContentByContentId(String contentId){
        return this.activityContentRepository.findOne(contentId);
    }


    /**
     * 查找出推荐的活动,返回一个
     *
     * @return
     */
    @Transactional
    public ActivityEntity getRecommendActivity() {
        if (logger.isDebugEnabled()) {
            logger.debug("getRecommendActivity() - start"); //$NON-NLS-1$
        }

        List<ActivityEntity> activityEntities = this.activityRepository.findRecommendByIsRecommend(1);
        ActivityEntity activityEntity = new ActivityEntity();
        if (null != activityEntities && 0 < activityEntities.size()) {
            activityEntity = activityEntities.get(0);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("getRecommendActivity() - end"); //$NON-NLS-1$
        }
        return activityEntity;
    }


    /**
     * 根据活动类型拿到活动数据
     *
     * @param size      大小
     * @param page      页码
     * @param type      活动类型
     * @param orderType 0表示积分排名赛,1表示系列赛
     * @return
     */
    @Transactional(readOnly = true)
    public Page<ActivityEntity> listActivityByActivityType(int size, int page, int type, String orderType) {
        if (logger.isDebugEnabled()) {
            logger.debug("listActivityByActivityType(int size={}, int page={}, int type={}, String orderType={}) - start", size, page, type, orderType); //$NON-NLS-1$
        }

        Sort sort = new Sort(Sort.Direction.ASC, "createdAt");
        if ("desc".equals(orderType)) {
            sort = new Sort(Sort.Direction.DESC, "createdAt");
        }
        //设置分页参数
        Pageable pageable = new PageRequest(page, (size <= 0) ? 3 : size, sort);
        Page<ActivityEntity> activityEntities = this.activityRepository.findActivityByActivityType(type, pageable);

        if (logger.isDebugEnabled()) {
            logger.debug("listActivityByActivityType(int, int, int, String) - end"); //$NON-NLS-1$
        }
        return activityEntities;
    }


    @Transactional
    public void deletedActivity(String activityId) throws ProjectException {
        List<ActivityContentEntity> contentEntities = this.findAllContentByActivityId(activityId);
        //删除活动内容
        for(ActivityContentEntity ac :contentEntities){
            this.deletedActivityContent(ac.getId());
        }
        //删除比赛内容
        List<MatchDetailsEntity> matchDetailsEntities =this.matchDetailsService.findMatchDetailsByActivityId(activityId);
        for (MatchDetailsEntity matchDetailsEntity : matchDetailsEntities){
            this.matchDetailsService.deleteMatchDetails(matchDetailsEntity.getId());
        }
        //删除关联票信息
        List<TicketEntity> ticketEntities = this.ticketService.findTicketByActivityId(activityId);
        for (TicketEntity ticketEntity :ticketEntities){
            this.ticketService.deletedTicket(ticketEntity.getId());
        }
        //移除用户活动表
        List<UserActivityEntity> userActivityEntities = this.userService.findAllUserByActivityIdWithoutStatus(activityId);
        for (UserActivityEntity userActivityEntity : userActivityEntities){
            this.userService.deleteUserActivity(userActivityEntity.getId());
        }
        this.activityRepository.delete(activityId);
    }

    @Transactional
    public void deletedActivityContent(String activityContentId){
        this.activityContentRepository.delete(activityContentId);
    }


    /**
     * 找到用户所有参加的活动
     * @param userId 用户id
     * @param type 比赛类型
     * @return
     */
    @Transactional
    public List<ActivityEntity> findUserAttendActivity(String userId,int type){
        List<ActivityEntity> activityEntities = new ArrayList<>();
        UserEntity userEntity = this.userService.findUserById(userId);
        List<UserActivityEntity> userActivityEntities = this.iUserActivityRepository.findAllActivityEntityByUserByUserId(userEntity);
        for (UserActivityEntity userActivityEntity : userActivityEntities){
          ActivityEntity activityEntity =  userActivityEntity.getActivityByActivityId();
          if (type == activityEntity.getActivityType()){
                activityEntities.add(activityEntity);
          }
        }
        return activityEntities;
    }



}
